import blesuite.replay.hci_parser as hci_parser
import argparse
import blesuite.replay.util
import json
import time

import logging
from logging.config import fileConfig

__version__ = "0.1"
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
logging.basicConfig(level=logging.DEBUG)


def create_help():
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--iface",
                        help="Device interface, retrieve using 'hcitool dev'")
    parser.add_argument("-d", "--address",
                        help="Device address, specified like 0E:3F:00:01:B2:0A")
    parser.add_argument("-t", "--address-type",
                        help="Address type, specified as public or random")
    parser.add_argument("-m", "--mtu", default=23,
                        help="Maxium Transmission Unit (MTU)")
    parser.add_argument("-p", "--parse",
                        help="Parse replay data from an HCI log file")
    parser.add_argument("-pp", "--parse-pcap",
                        help="Parse replay data from a PCAP log file, such as one generated by an Ubertooth")
    parser.add_argument("-if", "--infile",
                        help="Get replay data from a file created by this tool")
    parser.add_argument("-f", "--fetch",
                        help="Fetch replay data from Android device using adb",
                        action="store_true")
    parser.add_argument("-r", "--replay",
                        help="Replay the data, requires -f or -if",
                        action="store_true")
    parser.add_argument("-of", "--outfile",
                        help="Output file to write replay data to")

    parser.add_argument("-w", "--wait",
                        help="BLE-Replay will continuously wait for further communications, requires "
                             "force close to exit",
                        action="store_true")
    args = parser.parse_args()
    return args


def main():
    args = create_help()
    replay_data = []
    if args.infile:
        with open(args.infile, 'r') as infile:
            for line in infile:
                replay_data.append(json.loads(line))
    else:
        logparser = hci_parser.ATTWriteParser()
        if args.parse:
            logparser.load_file(args.parse)
        elif args.fetch:
            try:
                logparser.fetch_from_phone()
            except:
                return
        elif args.parse_pcap:
            logparser.load_file(args.parse_pcap, pcap_format=True)
        else:
            print "You must specify an input option (-if, -p, -f)"
            return
        replay_data = logparser.parse_att_writes()
        if args.outfile:
            logparser.write_to_file(args.outfile)

    if args.replay:
        if not (args.iface and args.address):
            print "You must specify an interface and device address"
            return
        blesuite.replay.util.gatt_writes(int(args.iface), args.address, args.address_type, replay_data,
                                         int(args.mtu), wait=args.wait)
        return
    elif args.outfile:
        return
    else:
        print "You must specify an output option (-r, -of)"
        return


main()
